package com.example.seed.interceptor;

import com.example.seed.entity.BaseEntity;
import com.example.seed.entity.BaseEntityDraft;
import com.example.seed.entity.BaseEntityProps;
import org.babyfish.jimmer.ImmutableObjects;
import org.babyfish.jimmer.sql.DraftInterceptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * 基本实体拦截器
 *
 * @author AAA
 * @date 2024/02/26
 */
@Component
public class BaseEntityDraftInterceptor implements DraftInterceptor<BaseEntity, BaseEntityDraft> {

    @Override
    public void beforeSave(@NotNull BaseEntityDraft draft, @Nullable BaseEntity original) {
        if (original == null) {
            if (!ImmutableObjects.isLoaded(draft, BaseEntityProps.CREATED_AT)) {
                draft.setCreatedAt(LocalDateTime.now());
                System.out.println("新数据填充新创建时间");
            }
        } else {
            if (!ImmutableObjects.isLoaded(draft, BaseEntityProps.UPDATED_AT)) {
                draft.setUpdatedAt(LocalDateTime.now());
                System.out.println("老数据自动填充更新时间");
            }
            if (!ImmutableObjects.isLoaded(draft, BaseEntityProps.UPDATER)) {
                draft.applyUpdater(it -> it.setId(2L));
                System.out.println("老数据自动填充更新人");
            }
        }
    }
}
